import 'dart:io';

import 'package:gate_cli/utils/intl_view/utils/project_intl.dart';
import 'package:gate_cli/utils/intl_view/utils/project_string_finder.dart';
import 'package:path/path.dart';
import 'package:yaml/yaml.dart';

class FindCommand {
  static final Set<WebSocket> _webSockets = {};

  static List<Map> findStrings() {
    return ProjectStringFinder.instance.find().map((e) => e.toJson()).toList();
  }

  static void import(List<ProjectDartFile> files, Map<String, String> keys) {
    final pubspec = loadYaml(
      File(join(Directory.current.path, 'pubspec.yaml')).readAsStringSync(),
    );
    final intlClassName = pubspec['flutter_intl']['class_name'];
    if (intlClassName == null) {
      return;
    }

    for (var element in files) {
      final file = File(element.file);
      final lines = file.readAsLinesSync();
      bool changed = false;
      for (var element in element.strings) {
        if (lines.length > element.lineNumber) {
          final lineText = lines[element.lineNumber];
          final key = keys[element.string];
          if (key != null) {
            final index = lineText.indexOf(element.string);
            if (index == -1) {
              continue;
            }
            final newText =
                lineText.replaceRange(index - 1, index + element.string.length + 1, '$intlClassName.current.$key');
            lines[element.lineNumber] = newText;
            changed = true;
          }
        }
      }
      if (changed) {
        file.writeAsStringSync(lines.join('\n'));
      }
    }

    final keysMap = keys.map((key, value) => MapEntry(value, key));

    ProjectIntl.instance.getArb('en').saveAll(keysMap);
  }

  void registerSocket(WebSocket socket) {
    _webSockets.add(socket);
    if (_webSockets.length == 1) {
      run();
    }

    socket.listen(
      (event) {
        //
      },
      onDone: () {
        _webSockets.remove(socket);
        if (_webSockets.isEmpty) {
          stop();
        }
      },
      onError: (error) {
        _webSockets.remove(socket);
        if (_webSockets.isEmpty) {
          stop();
        }
      },
      cancelOnError: true,
    );
  }

  bool _isRunning = false;

  void run() async {
    if (_isRunning) {
      return;
    }

    final directory = Directory(join(Directory.current.path, 'lib'));
    if (!directory.existsSync()) {
      return;
    }

    directory.list(recursive: true).listen((FileSystemEntity entity) {
      if (entity is File && entity.path.endsWith('.dart')) {
        // files.add(entity.path);
      }
    });
  }

  void stop() {
    //
  }
}
